package com.pf.service.impl;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.pf.dto.LoginUserReq;
import com.pf.dto.RegisterUserReq;
import com.pf.entity.RegisterUser;
import com.pf.enums.IsEffectiveEnum;
import com.pf.exception.BusinessException;
import com.pf.mapper.UserMapper;
import com.pf.service.UserService;
import com.pf.utils.MailUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * @author PanFei
 * @version 1.0.0
 * @createTime 2021/12/19 20:13
 */
@Slf4j
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private MailUtils mailUtils;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void registerUser(RegisterUserReq req) {
        Assert.notNull(req, "用户注册参数不能为空！");
        if (!req.getPassword().equals(req.getRePassword())) {
            throw new BusinessException("两次密码输入不一致！");
        }

        String activationCode = IdUtil.createSnowflake(1, 1).nextIdStr();
        String salt = RandomUtil.randomString(4);
        String password = SecureUtil.md5(req.getPassword() + salt);
        RegisterUser registerUser = RegisterUser.builder()
                .userId(IdUtil.randomUUID())
                .account(req.getAccount())
                .password(password)
                .salt(salt)
                .activationCode(activationCode)
                // 有效期1天
                .activationDeadline(LocalDateTime.now().plusDays(1))
                .isEffective(IsEffectiveEnum.INACTIVATED.getCode())
                .build();

        userMapper.insert(registerUser);

        // 发送邮件（可以异步发送邮件，如借助线程，消息队列等）
        List<String> toUsers = Lists.newArrayList("1968438358@qq.com");
        String subject = "激活注册账号";
        Map<String, Object> data = ImmutableMap.of("url", "http://localhost:8080/user/activateUser?activationCode=" + activationCode);
        String templateName = "registerNotice";
        mailUtils.sendTemplateThymeleaf(toUsers, null, subject, data, templateName);
    }

    @Override
    public void loginUser(LoginUserReq req) {
        RegisterUser queryUser = userMapper.selectOne(new LambdaQueryWrapper<RegisterUser>()
                .eq(RegisterUser::getAccount, req.getAccount())
        );
        if (queryUser == null) {
            throw new BusinessException("用户不存在！");
        }

        String checkPassword = SecureUtil.md5(req.getPassword() + queryUser.getSalt());
        if (!queryUser.getPassword().equals(checkPassword)) {
            throw new BusinessException("密码不正确！");
        }

        if (IsEffectiveEnum.INACTIVATED.getCode().equals(queryUser.getIsEffective())) {
            throw new BusinessException("账号未激活！");
        }
    }

    @Override
    public void activateUser(String activationCode) {
        RegisterUser queryUser = userMapper.selectOne(new LambdaQueryWrapper<RegisterUser>()
                .eq(RegisterUser::getActivationCode, activationCode)
        );
        if (queryUser == null) {
            throw new RuntimeException("激活码不正确！");
        }
        if (LocalDateTime.now().isAfter(queryUser.getActivationDeadline())) {
            throw new RuntimeException("激活码已过期！");
        }
        queryUser.setIsEffective(IsEffectiveEnum.ACTIVATED.getCode());
        userMapper.updateById(queryUser);
    }
}
